package com.lexton.toolbox.upload;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import com.lexton.util.excel.ExcelReadUtils;

/**
 * 
 * @author Jimmy
 *
 */
public class ProductReadUtil {
	public static List<Product> readfile(String filepath, List<Integer> sheets) throws FileNotFoundException, IOException {
		List<Product> result = new ArrayList<Product>();
		
		try {
			InputStream in = new FileInputStream(filepath);
			Workbook hssf = null;
			
			if (filepath.toLowerCase().endsWith("xls")) {
				hssf = new HSSFWorkbook(in);
			} else {
				hssf = new XSSFWorkbook(in);
			}
			for (int i=0; i<sheets.size(); i++) {
				Sheet sheet = hssf.getSheetAt(sheets.get(i));
				
				if (null == sheet) continue;
				
				for (int rowNum = 1; rowNum <= sheet.getLastRowNum(); rowNum++) {
					Row hssfRow = sheet.getRow(rowNum);
					if (null == hssfRow) continue;
					
					Product product = new Product();
					
					String sn = ExcelReadUtils.getCellFormatValue(hssfRow.getCell(1)).toString();
					if (sn != null && !"".equals(sn)) {
						product.setSn(sn);
						product.setSheetName(sheet.getSheetName());
						result.add(product);
					}
				}
			}
			
			hssf.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return result;
	}
	
	
}
